<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\user;

use app\api\model\dao\UserCurrency;
use app\library\Common;
use app\library\Error;
use app\library\PageBase;
use think\Exception;

class Signin extends PageBase
{

    private $objSignin;
    private $objUserCurrency;

    public function __construct()
    {
        parent::__construct();

        $this->objSignin = new \app\api\model\dao\Signin();
        $this->objUserCurrency = new UserCurrency();
    }

    public function myExcute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            throw new Exception('check token fail...', Error::ERR_NO_AUTH);
        }

        $ret = $this->objSignin->isSignin($this->user_id);
        if (false === $ret) {
            throw new Exception(' is signin fail...', Error::ERR_SYS);
        }

        if ($ret) {
            throw new Exception(' is signined...', Error::ERR_SIGNIN_EXIST);
        }

        // 构造参数
        $date = date('Ymd');
        $input = [
            'userid' => $this->user_id,
            'date' => $date,
        ];

        $ret = $this->objSignin->addSignin($input);
        if (false === $ret) {
            throw new Exception('add signin fail...[input: ' . json_encode($input) . ']', Error::ERR_SYS);
        }

        Common::addIntegral($this->user_id, 'signin');

        // 获取连续签到天数
        $sign_ret = $this->objSignin->getSigninByUserid($this->user_id);
        if (false === $sign_ret) {
            throw new Exception('get signin fail...[userid: ' . $this->user_id . ']', Error::ERR_SYS);
        }

        $sign_cnt = 0;
        $f = count($sign_ret) - 1;
        for ($i = $f; $i >= 0; $i--) {
            if (($f - $i) == ($sign_ret[$f]['date'] - $sign_ret[$i]['date'])) {
                $sign_cnt++;
            } else {
                break;
            }
        }
        $this->data['day'] = $sign_cnt;


    }
}
